<?php
namespace App\Job;

use Hyperf\AsyncQueue\Job;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use App\Service\RugbyArticleService;
use App\Helper\SeoHelper;

class RugbyArticleJob extends Job
{
    protected $product_id;
    protected $language_id;
    protected $keywords;
    protected $scenario;
    protected $productname;
    protected $productdesc;
    protected $webname;

    protected $logger;

    /**
     * @var RugbyArticleService
     */
    protected $rugbyArticleService;

    public function __construct(int $product_id, int $language_id, string $keywords, string $scenario, string $productname, string $productdesc, string $webname, int $article_id, string $image, LoggerFactory $loggerFactory)
    {
        $this->product_id = $product_id;
        $this->language_id = $language_id;
        $this->keywords = $keywords;
        $this->scenario = $scenario;
        $this->productname = $productname;
        $this->productdesc = $productdesc;
        $this->webname = $webname;
        $this->image = $image;
        $this->article_id = $article_id;

        $this->logger = $loggerFactory->get('article', 'article');
    }

    public function handle()
    {
        try {
            $conn = Db::connection($this->webname);

            $articleService = ApplicationContext::getContainer()->get(RugbyArticleService::class);
            $langs = [
                1 => "English",
                2 => "French",
            ];

            $langs_flipped = array_change_key_case(array_flip($langs), CASE_LOWER); // 转小写 key

            $existingArticles = $conn->table('oc_blog_product_related as rel')
                ->leftJoin('oc_blog_article_description as art', function ($join) {
                    $join->on('rel.article_id', '=', 'art.article_id');
                })
                ->where('rel.related_id', $this->product_id)
                ->where('art.language_id', $this->language_id)
                ->select('art.title')
                ->get();

            if($existingArticles){
                $existingTitles = array_map(function ($a) {
                    return $a->title;
                }, $existingArticles->toArray());
            }else{
                $existingTitles = [];
            }

            $article = $articleService->generateArticle([
                "name"              =>$this->productname,
                "desc"              =>$this->productdesc,
                "keywords"          =>$this->keywords,
                "scenario"          =>$this->scenario,
                "language"          =>$langs[$this->language_id],
                "blogs"             =>$existingTitles,
                "image"             =>$this->image,
                "add_article_id"    =>$this->article_id,
            ]);

            $article_id = (isset($article['article_id']) && (int)$article['article_id'] > 0) ? (int)$article['article_id'] : 0;

            if (!is_array($article) || empty($article['post_title']) || ($article_id == 0)) {
                $conn->table('oc_blog_article')
                    ->where('article_id', $article_id)
                    ->delete();

                $this->logger->warning("AI返回文章为空", [
                    'product_name' => $this->productname,
                    'webname' => $this->webname
                ]);

                return;
            }

            $this->logger->info("AI返回文章", $article);

            $conn->beginTransaction();

            $langKey = strtolower(trim($article['language_id']));
            $language_id = $langs_flipped[$langKey] ?? 1;

            $tagsRaw = $article['tags'];
            if (is_string($tagsRaw)) {
                $tags = implode(', ', array_filter(array_map('trim', explode(',', str_replace("'", '', $tagsRaw)))));
            } else {
                $tags = '';
            }

            $conn->table('oc_blog_article_description')->insert([
                'article_id'       => $article_id,
                'language_id'      => $language_id,
                'title'            => $article['post_title'],
                'description'      => $article['short_description'],
                'content'          => $article['description'],
                'tags'             => $tags,
                'meta_title'       => $article['meta_tag_title'],
                'meta_description' => $article['meta_tag_description'],
                'meta_keyword'     => $article['meta_keywords'],
            ]);

            $query = "blog/article&article_id=" . $article_id;
            $redirect = SeoHelper::generateSeoUrl($article['post_title']);

            $exists = $conn->table('oc_url_absolute')
                ->where('query', $query)
                ->where('language_id',$language_id)
                ->where('redirect', $redirect)
                ->count();

            if ($exists > 0) {
                $redirect .= '-' . $article_id;
            }

            $conn->table('oc_url_absolute')->insert([
                'query' => $query,
                'language_id' => $language_id,
                'redirect' => $redirect,
            ]);

            $conn->table('oc_blog_article_to_category')->insert([
                'article_id'       => $article_id,
                'category_id'      => 1,
            ]);

            $conn->table('oc_blog_product_related')
                ->where('article_id', $article_id)
                ->where('related_id', $this->product_id)
                ->delete();

            $conn->table('oc_blog_product_related')->insert([
                'article_id'       => $article_id,
                'related_id'      => $this->product_id,
            ]);

            $conn->table('oc_blog_article_to_store')->insert([
                'article_id'       => $article_id,
                'store_id'      => 0,
            ]);

            $conn->commit();

            $this->logger->info("文章生成成功", [
                'product_name' => $this->productname,
                'article_id' => $article_id,
                'webname' => $this->webname
            ]);
        } catch (\Throwable $e) {
            $conn->rollBack();
            $this->logger->error("任务处理失败", [
                'product_name' => $this->productname,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }
}
